# -*- coding: utf-8 -*-
# =============================================================================
#     FileName:
#         Desc:
#       Author:
#        Email:
#     HomePage:
#      Version:
#   LastChange:
#      History:
# =============================================================================
import json

from utils.log_helper import LogHelper
from utils.mysql_archiver import MyArchiveType
from utils.mysql_server import MySQLServer

logger = LogHelper.get_logger()


class TaskConfig(object):
    def __init__(self):
        self.task_name = ""
        self.task_type = ""
        self.source_table_name = ""
        self.target_table_name = ""
        self.etl_table_name = ""
        self.data_condition = ""
        self.max_primary_key = ""
        self.min_primary_key = ""

    @classmethod
    def get_task_from_json(cls, task_json):
        task = TaskConfig()
        task.task_name = task_json.get("task_name")
        task.source_table_name = task_json.get("source_table_name")
        task.target_table_name = task_json.get("target_table_name", "")
        task.etl_table_name = task_json.get("etl_table_name", "")
        task.max_primary_key = task_json.get("max_primary_key", "AUTO")
        task.min_primary_key = task_json.get("min_primary_key", "AUTO")
        task_type = task_json.get("task_type", "")
        if str(task_type).strip().lower() == "mysql_loop_delete":
            task.task_type = MyArchiveType.MYSQL_LOOP_DELETE
        elif str(task_type).strip().lower() == "mysql_loop_copy":
            task.task_type = MyArchiveType.MYSQL_LOOP_COPY
        else:
            task.task_type = MyArchiveType.MYSQL_LOOP_ARCHIVE
        if str(task.target_table_name).strip() == "":
            task.target_table_name = None
        if str(task.etl_table_name).strip() == "":
            task.etl_table_name = None
        data_condition = task_json.get("data_condition", ["1<>1"])
        if type(data_condition) == list:
            data_condition = "\n".join(data_condition)
        task.data_condition = data_condition
        return task


class BaseConfig(object):
    def __init__(self):
        self.is_dry_run = True
        self.source_server = None
        self.target_server = None
        self.etl_server = None
        self.archive_tasks = list()
        self.batch_scan_rows = 1000
        self.batch_insert_rows = 100
        self.batch_sleep_seconds = 1
        self.max_query_seconds = 100

    @classmethod
    def get_server_from_config(cls, config_item):
        if config_item is None:
            return None
        else:
            return MySQLServer(
                mysql_host=config_item.get("host_name"),
                mysql_port=config_item.get("host_port", 3306),
                mysql_user=config_item.get("user_name"),
                mysql_password=config_item.get("user_password"),
                mysql_charset=config_item.get("mysql_charset", "utf8mb4"),
                database_name=config_item.get("database_name"),
                connect_timeout=config_item.get("connect_timeout", 60),
            )

    @classmethod
    def get_base_config(cls, config_file_path):
        with open(config_file_path, 'r', encoding='utf-8') as file_handler:
            dict_configs = json.load(file_handler)
        bc = BaseConfig()
        bc.source_server = cls.get_server_from_config(dict_configs.get("source_server"))
        bc.target_server = cls.get_server_from_config(dict_configs.get("target_server", None))
        bc.etl_server = cls.get_server_from_config(dict_configs.get("etl_server", None))
        base_configs = dict_configs["base_configs"]
        bc.batch_scan_rows = base_configs.get("batch_scan_rows", 1000)
        bc.batch_insert_rows = base_configs.get("batch_insert_rows", 1000)
        bc.batch_sleep_seconds = base_configs.get("batch_sleep_seconds", 1)
        bc.max_query_seconds = base_configs.get("max_query_seconds", 1000)
        bc.is_dry_run = base_configs.get("is_dry_run", True)
        task_items = dict_configs.get("task_items")
        for task_item in task_items:
            bc.archive_tasks.append(TaskConfig.get_task_from_json(task_item))
        return bc
